﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.IO;
using System.Security.AccessControl;
using System.Configuration;
using System.Windows.Forms;
using System.Reflection;
using Utils;

namespace Settings
{
    public class AppSetting
    {
        #region Connection
        public static string ConnectionString
        {
            get { return System.Configuration.ConfigurationManager.ConnectionStrings["MSSQLConnectionString"].ConnectionString; }
            set
            {
                var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
                connectionStringsSection.ConnectionStrings["MSSQLConnectionString"].ConnectionString = value;
                config.Save();
                ConfigurationManager.RefreshSection("connectionStrings");
                _SqlConnectionStringBuilder = new SqlConnectionStringBuilder(value);
            }
        }
        public static SqlConnection GetConnection()
        {
            try
            {
                SqlConnection conn = new SqlConnection(ConnectionString);
                conn.Open();
                return conn;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        static SqlConnectionStringBuilder _SqlConnectionStringBuilder;
        public static SqlConnectionStringBuilder ConnectionStringBuilder
        {
            get
            {
                if (_SqlConnectionStringBuilder == null) _SqlConnectionStringBuilder = new SqlConnectionStringBuilder(ConnectionString);
                return _SqlConnectionStringBuilder;
            }
        }

        public static string DataSource
        {
            get
            {
                return ConnectionStringBuilder.DataSource;
            }
            set
            {
                ConnectionStringBuilder.DataSource = value;
                ConnectionString = ConnectionStringBuilder.ConnectionString;
            }
        }

        public static string Database
        {
            get
            {
                return ConnectionStringBuilder.InitialCatalog;
            }
            set
            {
                ConnectionStringBuilder.InitialCatalog = value;
                ConnectionString = ConnectionStringBuilder.ConnectionString;
            }
        }

        public static string UserID
        {
            get
            {
                return ConnectionStringBuilder.UserID;
            }
            set
            {
                ConnectionStringBuilder.UserID = value;
                ConnectionString = ConnectionStringBuilder.ConnectionString;
            }
        }

        public static string Password
        {
            get
            {
                return ConnectionStringBuilder.Password;
            }
            set
            {
                ConnectionStringBuilder.Password = value;
                ConnectionString = ConnectionStringBuilder.ConnectionString;
            }
        }
        #endregion

        #region AlertSystemConnection
        public static string AlertSystemConnectionString
        {
            get { return System.Configuration.ConfigurationManager.ConnectionStrings["MSSQLAlertSystemConnectionString"].ConnectionString; }
            set
            {
                var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
                connectionStringsSection.ConnectionStrings["MSSQLAlertSystemConnectionString"].ConnectionString = value;
                config.Save();
                ConfigurationManager.RefreshSection("connectionStrings");
                _AlertSystemConnectionStringBuilder = new SqlConnectionStringBuilder(value);
            }
        }
        public static SqlConnection GetAlertSystemConnection()
        {
            try
            {
                SqlConnection conn = new SqlConnection(AlertSystemConnectionString);
                conn.Open();
                return conn;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        
        static SqlConnectionStringBuilder _AlertSystemConnectionStringBuilder;
        public static SqlConnectionStringBuilder AlertSystemConnectionStringBuilder
        {
            get
            {
                if (_AlertSystemConnectionStringBuilder == null) _AlertSystemConnectionStringBuilder = new SqlConnectionStringBuilder(AlertSystemConnectionString);
                return _AlertSystemConnectionStringBuilder;
            }
        }

        public static string AlertSystemDataSource
        {
            get
            {
                return AlertSystemConnectionStringBuilder.DataSource;
            }
            set
            {
                AlertSystemConnectionStringBuilder.DataSource = value;
                AlertSystemConnectionString = AlertSystemConnectionStringBuilder.ConnectionString;
            }
        }

        public static string AlertSystemDatabase
        {
            get
            {
                return AlertSystemConnectionStringBuilder.InitialCatalog;
            }
            set
            {
                AlertSystemConnectionStringBuilder.InitialCatalog = value;
                AlertSystemConnectionString = AlertSystemConnectionStringBuilder.ConnectionString;
            }
        }

        public static string AlertSystemUserID
        {
            get
            {
                return AlertSystemConnectionStringBuilder.UserID;
            }
            set
            {
                AlertSystemConnectionStringBuilder.UserID = value;
                AlertSystemConnectionString = AlertSystemConnectionStringBuilder.ConnectionString;
            }
        }

        public static string AlertSystemPassword
        {
            get
            {
                return AlertSystemConnectionStringBuilder.Password;
            }
            set
            {
                AlertSystemConnectionStringBuilder.Password = value;
                AlertSystemConnectionString = AlertSystemConnectionStringBuilder.ConnectionString;
            }
        }
        #endregion

        private static string _ApplicationName;
        public static string ApplicationName
        {
            get
            {
                if(string.IsNullOrWhiteSpace(_ApplicationName)) _ApplicationName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
                return _ApplicationName;
            }
        }

        private static Version _ApplicationVersion;
        public static Version ApplicationVersion
        {
            get
            {
                if (_ApplicationVersion == null) _ApplicationVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
                return _ApplicationVersion;
            }
        }
        
        public static string AppModulesPath
        {
            get
            {
                string appPath = Path.GetDirectoryName(typeof(AppSetting).Assembly.Location);
                string modulPath = System.Configuration.ConfigurationManager.AppSettings["App_Modules_Path"];
                if (modulPath != null)
                {
                    string appModulePath = Path.Combine(appPath, modulPath);

                    if (!Directory.Exists(appModulePath))
                    {
                        Directory.CreateDirectory(appModulePath);
                    }
                    return appModulePath;
                }
                return "";
            }
        }

        public static string AppBackupPath
        {
            get
            {
                string appPath = Path.GetDirectoryName(typeof(AppSetting).Assembly.Location);
                string backupPath = System.Configuration.ConfigurationManager.AppSettings["App_Backup_Path"];
                string appbackupPath = Path.Combine(appPath, backupPath);

                if (!Directory.Exists(appbackupPath))
                {
                    Directory.CreateDirectory(appbackupPath);
                }
                return appbackupPath;
            }
        }

        public static string SmsOutWaitingBackupFileName
        {
            get
            {
                return Path.Combine(AppBackupPath, System.Configuration.ConfigurationManager.AppSettings["SmsOutWaitingBackupFileName"]);
            }
        }

        public static string SmsOutReportBackupFileName
        {
            get
            {
                return Path.Combine(AppBackupPath, System.Configuration.ConfigurationManager.AppSettings["SmsOutReportBackupFileName"]);
            }
        }

        public static string SmsRouterReportBackupFileName
        {
            get
            {
                return Path.Combine(AppBackupPath, System.Configuration.ConfigurationManager.AppSettings["SmsRouterReportBackupFileName"]);
            }
        }

        public static string SmsInWaitingBackupFileName
        {
            get
            {
                return Path.Combine(AppBackupPath, System.Configuration.ConfigurationManager.AppSettings["SmsInWaitingBackupFileName"]);
            }
        }

        public static string SmsInStatisticBackupFileName
        {
            get
            {
                return Path.Combine(AppBackupPath, System.Configuration.ConfigurationManager.AppSettings["SmsInStatisticBackupFileName"]);
            }
        }

        /// <summary>
        /// Đường dẫn đến file LogBackup.xml
        /// </summary>
        public static string LogBackupFileName
        {
            get
            {
                return Path.Combine(AppBackupPath, System.Configuration.ConfigurationManager.AppSettings["LogBackupFileName"]);
            }
        }

        /// <summary>
        /// Đường dẫn đến thư mục RouterLogs (text file)
        /// </summary>
        public static string RouterLog_Path
        {
            get
            {
                return Path.Combine(Application.StartupPath, System.Configuration.ConfigurationManager.AppSettings["RouterLog_Path"]);
            }
        }

        public static string MORouterLog_Path
        {
            get
            {
                return Path.Combine(RouterLog_Path, System.Configuration.ConfigurationManager.AppSettings["MORouterLog_Path"]);
            }
        }

        public static string MTRouterLog_Path
        {
            get
            {
                return Path.Combine(RouterLog_Path, System.Configuration.ConfigurationManager.AppSettings["MTRouterLog_Path"]);
            }
        }

        public static int ConnectionTimeout
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["ConnectionTimeout"].ToInt();
            }
        }

        public static int ServiceTimeOut
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["ServiceTimeOut"].ToInt();
            }
        }

        public static int BatchSize
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["BatchSize"].ToInt();
            }
        }

        public static int RetryOnTimeoutReqTimes
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["RetryOnTimeoutReqTimes"].ToInt();
            }
        }

        public static int RetryOnFailReqTimes
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["RetryOnFailReqTimes"].ToInt();
            }
        }

        public static int ReadDataDuration
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["ReadDataDuration"].ToInt();
            }
        }

        public static int UpdateDataDuration
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["UpdateDataDuration"].ToInt();
            }
        }

        public static int AlertRouterDuration
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["AlertRouterDuration"].ToInt();
            }
        }

        public static int MaxQueueElement
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["MaxQueueElement"].ToInt();
            }
        }

        public static string GetAppSetting(string key)
        {
            return System.Configuration.ConfigurationManager.AppSettings[key] ?? "";
        }

        public struct Status
        {
            public const string SENTGATEWAY = "SENTGATEWAY";
            public const string SENTPARTNER = "SENTPARTNER";
            public const string SENT = "SENT";
            public const string PENDING = "PENDING";
            public const string TIMEOUT = "TIMEOUT";
            public const string FAIL = "FAIL";
        }

        public struct RouterType
        {
            public const string MOROUTER = "MOROUTER";
            public const string MTROUTER = "MTROUTER";
        }

        public struct WarningType
        {
            public const string mo_error = "mo_error";
            public const string mt_error = "mt_error";
            public const string application_error = "application_error";
            public const string warning = "warning";
            public const string database = "database";
        }

        private static string _SystemID = "emarketing";
        public static string SystemID { get { return _SystemID; } }

        public static bool SystemConnected = false;
        public static bool AlertSystemConnected = false;
    }
}